package com.baidu.ueditor.upload;

import java.util.Map;

import org.apache.commons.codec.binary.Base64;

import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;
import com.qingxin.sys.support.UploadFile;
import com.qingxin.sys.utils.UploadUtil;

public final class Base64Uploader {

	public static State save(String content, Map<String, Object> conf) {
		
		byte[] data = decode(content);

		long maxSize = ((Long) conf.get("maxSize")).longValue();

		if (!validSize(data, maxSize)) {
			return new BaseState(false, AppInfo.MAX_SIZE);
		}

		String suffix = FileType.getSuffix("JPG");

//		String savePath = PathFormat.parse((String) conf.get("savePath"),
//				(String) conf.get("filename"));
//		
//		savePath = savePath + suffix;
//		String physicalPath = (String) conf.get("rootPath") + savePath;

		//修改，使用自定义文件保存目录
		String savedir = (String) conf.get("savedir");
		String dir = UploadFile.getSaveDirByKey(UploadFile.DIR_UE_UPLOAD);
		dir = dir + "/" + savedir;//分类型保存
		//文件保存名称
		String filename = UploadUtil.generateDateFolderName()+"/"+ UploadUtil.generateLongFilename();
		String fileSaveName = filename + suffix;
		
		String physicalPath = UploadFile.getFilerootRealpath(dir+"/"+fileSaveName);
		
		//保存文件
		State storageState = StorageManager.saveBinaryFile(data, physicalPath);

		if (storageState.isSuccess()) {
			//storageState.putInfo("url", PathFormat.format(savePath));
			storageState.putInfo("url", UploadFile.getFileUrl(dir+"/"+fileSaveName));
			storageState.putInfo("type", suffix);
			storageState.putInfo("original", "");
		}

		return storageState;
	}

	private static byte[] decode(String content) {
		return Base64.decodeBase64(content);
	}

	private static boolean validSize(byte[] data, long length) {
		return data.length <= length;
	}
	
}